﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Xml.Serialization;

namespace PlistParser
{
    class ConvertXML
    {
        List<DataType> DataList{get;set;}

        public ConvertXML (List<DataType> datalist)
	    {
            DataList = datalist;
	    }
        
        public XDocument xdoc = new XDocument(new XDocument(new XDeclaration("1.0", "utf-8", "yes"), new XElement("Model")));
        public XDocument creatXML()
        {
            xdoc.Element("Model").SetAttributeValue("id","1");
            foreach (var item in DataList)
            {
                if (DataList[0].childrenID.Contains(item.ID))
                {
                    //xdoc.Element("Model").Add(new XElement(item.DataName, item.Value));
                    XElement newElement = xdoc.Descendants().Where(e => e.Attribute("id").Value == "1").First();
                    newElement.Add(new XElement(item.DataName, item.Value, new XAttribute("id", item.ID)));
                    if (item.ValueType == EnumValueType.ARRAY||item.ValueType == EnumValueType.DICT)
                    {
                        //XElement newElement = xdoc.Element("Model").Element(item.DataName);
                        creatOnce(newElement, item);
                    }
                    
                }
            }
            return xdoc;
        }

        public void creatOnce(XElement doc,DataType parent)
        {
            foreach (var item in DataList)
            {
                if (parent.childrenID.Contains(item.ID))
                {
                    string parentID = parent.ID.ToString();
                    XElement newElement = doc.Descendants().Where(e => e.Attribute("id").Value.Equals(parentID)).First();
                    newElement.Add(new XElement(item.DataName, item.Value, new XAttribute("id", item.ID)));
                    if (item.ValueType == EnumValueType.ARRAY||item.ValueType == EnumValueType.DICT)
                    {
                        //nowElement = nowElement.Element(item.DataName);
                        creatOnce(newElement,item);
                    }
                }
            }
        }

    }
}
